/**
 * The contents of this file are subject to the license and copyright detailed in the LICENSE and NOTICE files at the root of the source tree and available online at
 * http://www.askosi.org/license.html
 */
package be.destin.skos.core;

import java.util.LinkedList;

/**
 * @author Christophe Dupriez
 *
 */
public class CountList extends LinkedList<Count> {

	public static final long serialVersionUID = 1;
	public static final String anyIndex = "";

	public Count getIndex(String index) {
		if (this.size() <= 0) return null;
		for (Count x : this) {
			if (x.getRole().equals(index)) {
				return x;
			}
		}
		if (!anyIndex.equals(index)) return null;
		return this.getFirst();
	}

	/* Set the entry for a given index role */
	public void setIndex(String indX, Count aValue) {
		if (indX == null) indX = ""; // empty role is allowed
		else indX = indX.trim();
		if (aValue == null) {
			for (Count aRef : this) {
				String anIndex = aRef.getRole();
				if (anIndex.equals(indX)) {
					aRef.setCount(0);
					return;
				}
				else if ( indX != anyIndex && anIndex.startsWith(indX)) {
					aRef.setCount(0);
					return;
				}
			}
		} else {
			for (Count anEntry : this) {
				String anIndex = anEntry.getRole();
				if (anIndex.equals(indX)) {
					anEntry.setCount(aValue.getCount());
					anEntry.setCategory(aValue.getCategory());
					anEntry.setPure(aValue.isPure());
					return;
				}
				else if ( indX != anyIndex && anIndex.startsWith(indX)) {
					anEntry.setCount(aValue.getCount());
					anEntry.setCategory(aValue.getCategory());
					anEntry.setPure(aValue.isPure());
					return;
				}
			}
			Count aRef = new Count(aValue);
			aRef.setRole(indX);
			this.add(aRef);
		}
	}

	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append(this.size());
		result.append(" counts:[");
		for (Count aCount: this) {
			result.append(aCount.toString());
			result.append(';');
		}
		return result.append(']').toString();
	}
}
